#include "audiostreamencoder.h"

AudioStreamEncoder::AudioStreamEncoder()
{
}

void AudioStreamEncoder::run()
{

//    qDebug() << QFontDatabase::addApplicationFont("res/fonts/Museo_Cyrillic_500.ttf");

//    QFile museoFontFile(":/res/fonts/Museo_Cyrillic_500.ttf");
//    qDebug() << QFontDatabase::addApplicationFontFromData(museoFontFile.readAll());
//    qDebug() << museoFontFile.size();

//    this->outputFile.setFileName("/home/anderson/test.raw");
//    this->outputFile.open(QIODevice::WriteOnly | QIODevice::Truncate);

//    this->dataBufferStream->set  QDataStream(this->dataBuffer);

    QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
    qDebug() << "Supported codecs:";
    foreach(QString codec, info.supportedCodecs())
    {
        qDebug() << " - " << codec;
    }
    qDebug() << "Available devices:";
    foreach(QAudioDeviceInfo deviceInfo, info.availableDevices(QAudio::AudioInput))
    {
        qDebug() << " - " << deviceInfo.deviceName();
    }

    QAudioFormat format;
    format.setFrequency(8000);
    format.setChannels(1);
    format.setSampleSize(8);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleRate(QAudioFormat::UnSignedInt);

    if(!info.isFormatSupported(format))
    {
        qWarning() << "Default format not supported, trying nearest";
//        qDebug() << "Error: " << this->audioInput->error();
        format = info.nearestFormat(format);
    }

    qDebug() << tr("Selected format frequency: %1").arg(QString::number(format.frequency()));
    qDebug() << tr("Selected format codec: %1").arg(format.codec());
    qDebug() << tr("Selected sample size: %1").arg(QString::number(format.sampleSize()));

    this->audioInput = new QAudioInput(format);

    this->audioInput->setBufferSize(262144);
//    this->audioInput->start(this->outputFile);

    this->inputDevice = this->audioInput->start();
//    qDebug() << this->audioInput->error();
    qDebug() << "Started";

//    this->dataDevice = this->audioInput->start();
    while(1)
    {
        QByteArray buffer = this->inputDevice->readAll();
        this->dataBuffer.append(buffer);

///        qDebug() << "Reading voice, got bytes: " << buffer.length() << ", bytes in buffer: " << this->dataBuffer.length();
        if(this->dataBuffer.length() > 2000)
        {
            qDebug("Buffer is full, emitting signal");
            emit chunkReady(this->dataBuffer);
            this->dataBuffer.clear();
        }

        this->usleep(50000);
    }
}

void AudioStreamEncoder::startCapture(QThread *thread)
{
    this->parentThread = thread;
    this->isRunning = true;
    this->start();
}

void AudioStreamEncoder::stopCapture()
{
    this->audioInput->stop();
    this->isRunning = false;
}
